import Emitter from 'events'
import { ModelEvent } from '.'

export default class ContentModel extends Emitter {

  private ctx = ''

  constructor() {
    super()
  }

  get body() {
    return this.ctx
  }

  _notify() {
    this.emit(ModelEvent.CONTENT_UPDATE)
  }

  insert(index: number, data: string) {
    this.ctx = this.ctx.substring(0, index) + data + this.ctx.substring(index)
    this._notify()
  }
  delete(index: number, length: number) {
    let deleted = this.ctx.substring(index, index + length)
    this.ctx = this.ctx.substring(0, index) + this.ctx.substring(index + length)
    this._notify()
    return deleted
  }
  replace(index: number, length: number, data: string) {
    let deleted = this.ctx.substring(index, index + length)
    this.ctx = this.ctx.substring(0, index) + data + this.ctx.substring(index + length)
    this._notify()
    return deleted
  }
}